<template>
	<li :class="{ completed: todo.done, editing: editing }" class="todo">
		<div class="view">
			<input :checked="todo.done"
				   class="toggle"
				   type="checkbox"
				   @change="toggleTodo( todo)" />
			<label @dblclick="editing = true" v-text="todo.text"></label>
			<button class="destroy" @click="deleteTodo( todo )"></button>
		</div>
		<input v-show="editing"
			   v-focus="editing"
			   :value="todo.text"
			   class="edit"
			   @keyup.enter="doneEdit"
			   @keyup.esc="cancelEdit"
			   @blur="doneEdit" />
	</li>
</template>

<script>
	module.exports = {
		name: 'Todo',
		directives: {
			focus(el, { value }, { context }) {
				if (value) {
					context.$nextTick(() => {
						el.focus()
					})
				}
			}
		},
		props: {
			todo: {
				type: Object,
				default: function () {
					return {}
				}
			}
		},
		data() {
			return {
				editing: false
			}
		},
		methods: {
			deleteTodo(todo) {
				this.$emit('deletetodo', todo)
			},
			editTodo({ todo, value }) {
				this.$emit('edittodo', { todo, value })
			},
			toggleTodo(todo) {
				this.$emit('toggletodo', todo)
			},
			doneEdit(e) {
				const value = e.target.value.trim()
				const { todo } = this
				if (!value) {
					this.deleteTodo({
						todo
					})
				} else if (this.editing) {
					this.editTodo({
						todo,
						value
					})
					this.editing = false
				}
			},
			cancelEdit(e) {
				e.target.value = this.todo.text
				this.editing = false
			}
		}
	}
</script>
